package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.*;
import bean.Admin;
import bean.Exam;
import bean.Question;

public class AddExam extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req,res);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	int pageSize=2;
    int showPage;
    ExamDao dao=new ExamDao();
	List<Exam> all=dao.allExam();
	int recordCount=all.size();
	int pageCount=(recordCount%pageSize==0)?(recordCount/pageSize):(recordCount/pageSize+1);
	String integer=req.getParameter("showPage");
	String eid=req.getParameter("eid");
    if(eid!=null&&eid!=""){
    	try{
    		dao.deleteExamByEid(eid);
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
    }
    
	if(integer==null){
		ExamDao ed=new ExamDao();
		String aid=req.getParameter("aid");
		String ename=req.getParameter("ename");
		String score=req.getParameter("score");
		int hour=Integer.parseInt(req.getParameter("hour").toString().trim());
		int minite=Integer.parseInt(req.getParameter("minite").toString().trim());
		aid=new String(aid.getBytes("iso-8859-1"));
		ename=new String(ename.getBytes("iso-8859-1"));
		score=new String(score.getBytes("iso-8859-1"));
		Exam e=new Exam("",aid,ename,hour,minite,score);
		try{
			ed.addExam(e);
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		integer="1";
    }
    try{
    	showPage=Integer.parseInt(integer);
    }catch(NumberFormatException e){
     showPage=1;
    }
    if(showPage<=1){
     showPage=1;
    }
    if(showPage>=pageCount){
     showPage=pageCount;
    }
   
    if(showPage!=pageCount){
    	int position=(showPage-1)*pageSize+1;
    	ArrayList<Exam> el=dao.getOnePage(position, pageSize);
    	req.setAttribute("elist", el);
    }
    else{
    	int position=(showPage-1)*pageSize+1;
    	ArrayList<Exam> el=dao.getLastPage(position);
    	req.setAttribute("elist", el);
    }
    req.setAttribute("pageCount", pageCount);
    req.setAttribute("showPage", showPage);
	req.getRequestDispatcher("exammanage.jsp").forward(req,res);
}
}
